var cash = {
    /*
        会缓存头一天的数据
    */
    updateTime: {       //近更新时间
        action: 0,
        inventory: 0,
    },

    load: function(callback) {
       var updateTime = this.updateTime;

        async.series([
            function(cb) {
                var sql = "SELECT max(time) as maxTime FROM cash";
                gStat.pool.query(sql, function(err, res, fields) {
                    if (!err) {
                        updateTime.action = (res[0].maxTime || 0);
                    }
                    cb(err);
                });
            },
            function(cb) {
                var sql = "SELECT max(time) as maxTime FROM inventory";
                gStat.pool.query(sql, function(err, res, fields) {
                    if (!err) {
                        updateTime.inventory = (res[0].maxTime || 0);
                    }
                    cb(err);
                });
            }
        ], function(err, results) {
            callback(err);
        });
    },

    stat: function(callback) {
        var minTime = this.updateTime.action + 86400;
        var maxTime = (new Date()).zeroTime().getStamp() - 86400;
        if (maxTime <= minTime) {
            callback(); return;
        }

        query = {
            'minSid':1,
            'maxSid':UINT16_MAX,
            'minTime':minTime,
            'maxTime':maxTime,
        }
        
        var resp = {code:0, desc:'', data:[]};
        logic.cash.actionDay(query, resp, function() {
            if (resp.code) {
                callback(util.format('action %s', resp.desc)); return;
            }
            
            if (resp.data.length <= 0) {
                callback(); return;
            }

            var values = [];
            for (var i = 0, max = resp.data.length; i < max; ++i) {
                var data = resp.data[i];
                values.push(util.format("(%d, %d, '%s', '%s', %d, %d)", data[1], data[0], data[2], data[3], data[4], data[5]));
            }

            var sql = util.format("INSERT INTO cash(`time`, `sid`, `mod`, `act`, `cash`, `times`) VALUES%s;", values.join(','));
            gStat.pool.query(sql, function(err) {
                if (!err) {
                    this.updateTime.action = maxTime;
                }
                callback(err);
            }.bind(this));
        }.bind(this));
    },
}

exports.cash = cash;
